const { query } = require("express");
const querystring = require("querystring");

const handleBlogRoute = require("./src/routes/blog");

//处理post数据
const getPostData = (req) => {
  return new Promise((reslove, reject) => {
    //如果不是post请求
    if (req.method !== "POST") {
      reslove({});
      return;
    }
    //如果post上传的数据不是json格式
    if (req.headers["content-type"] !== "application/json") {
      reslove({});
      return;
    }
    let postData = "";

    req.on("data", (chunk) => {
      postData += chunk.toString();
    });

    req.on("end", () => {
      if (!postData) {
        reslove({});
        return;
      }
      reslove(JSON.parse(postData));
    });
  });
};

const serverhandler = (req, res) => {
  res.setHeader("Content-Type", "application/json");
  //获取path参数
  const url = req.url;
  req.path = url.split("?")[0];
  //解析query
  req.query = querystring.parse(url.split("?")[1]);
 
  //处理post数据异步
  getPostData(req).then((postData)=>{
    req.body = postData;
    //处理博客路由
    const blogdataPromise = handleBlogRoute(req,res);
    if (blogdataPromise) {
        blogdataPromise.then((blogdata)=>{
            res.end(JSON.stringify(blogdata));
        }) 
        return;
    }
    //未匹配到任何路由
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.write("404 NOT Found");
    res.end();
  })
 
};
module.exports = serverhandler;
